const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    partTeamData: {
      memberData: [
      ],
      teamCard: {
        middleTitle: '我参与的队伍',
        middleBtnText: '',
        rightCapsule: '',
        memberTotal: undefined,
        status: -1,
      },
    },
    appMsg: {
      show: false,
      type: 'none'
    },
    myTeamData: [
    ],
    activityId: '', //活动id
    // activityId: '81T1RWCYJHM1MD9YS869', //活动id
    isComplete: -1, // 是否完成 1是0否
    status: -1, // 是否兑换 1是0否
    currentUserId: undefined, // 当前用户id
    carryBtnText: '', // 完成后按钮内容
    notCarryBtnText: '', // 未完成按钮内容
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    this.data.myTeamData = []
    // 拿到活动id
    this.data.activityId = app.globalData.activityData.activityId
    this.getCurrentTeamInfo()
  },
  /**
   * @see 获取队伍列表
   */
  getCurrentTeamInfo () {
    wx.showLoading({ title: '加载中' })
    const { activityId } = this.data
    const request = {
      activityId,
    }
    // 调用获取元素接口
    wx.$API['eventConfiguration/getElements']({ activityId, eIndex: [3, 5] }).then(res => {
      return new Promise((resolve, reject) => {
        if (!res.data.length) {
          this.setData({
            appMsg: { type: 'err', show: true }
          })
          wx.hideLoading()
          return
        }
        let str = JSON.parse(res.data[0].content) // 邀请助力
        let teamList = JSON.parse(res.data[1].content)
        this.data.inviteConfig = str
        this.data.carryBtnText = teamList.complete // 完成按钮内容
        this.data.notCarryBtnText = teamList.notComplete // 未完成按钮内容
        resolve()
      })
    })
      .then(() => {
        const { inviteConfig, carryBtnText, notCarryBtnText } = this.data
        // 获取队伍列表
        wx.$API['eventConfiguration/listManageOrganize'](request)
          .then(res => {
            let { data } = res
            if (!data.length) {
              this.setData({
                appMsg: { type: 'none', show: true }
              })
              wx.hideLoading()
              return
            }
            data.forEach((team, index) => {
              // 队友列表
              let { teammates } = team
              let {
                status, // 是否兑换
                isComplete, // 是否完成 
                activityTarget, // 最大人数
                id, // 当前用户id
                isCaptain, // 是否队长
                participateTime, // 创建时间
                completeTime, // 完成时间
                exchangeTime, // 兑换时间
              } = team
              delete team.teammates
              // 数据整合
              let arr = [team, ...teammates]
              // 拿出队长数据
              let leader = arr.filter(v => v.isCaptain === 1)
              let captainId = leader[0].id
              app.globalData.activityData.captainId = captainId
              // 拿出队员数据
              teammates = arr.filter(v => v.isCaptain !== 1)
              arr = teammates.length > 0 ? [...leader, ...teammates] : [...leader || arr[0]]
              let timeArr = []
              let showBtnText = ''
              // 是否完成组队,显示不同按钮内容 
              if (isComplete) {
                showBtnText = carryBtnText;
                // console.log('任务已完成', inviteConfig.complete, completeTime)
              } else {
                showBtnText = notCarryBtnText
                // console.log('任务未完成', inviteConfig.notComplete)
              }
              // 队伍列表需要显示组队时间
              timeArr.push(participateTime)
              // 是否兑换,显示不同按钮内容
              if (status !== 2) {
                timeArr.push(exchangeTime)
                // console.log('现在的状态是已兑换', timeArr);
              }
              if (isCaptain === 0) {
                this.setData({
                  ['partTeamData.memberData']: arr,
                  ['partTeamData.teamCard']: {
                    timeArr,
                    middleTitle: '我参与的队伍',
                    middleBtnText: showBtnText,
                    rightCapsule: '查看详情',
                    memberTotal: activityTarget,
                    status: status,
                    isComplete,
                    id,
                    inviteConfig: this.data.inviteConfig,
                    captainId, // 队长id
                    isCaptain,
                  },
                })
              } else if (isCaptain === 1) {
                let join = [{
                  captainId, // 队长id
                  memberData: arr,
                  teamCard: {
                    timeArr,
                    middleBtnText: showBtnText,
                    middleTitle: this.data.myTeamData.length === 0 && '我的队伍',
                    rightCapsule: '查看详情',
                    memberTotal: activityTarget,
                    status: status,
                    isComplete,
                    id,
                    inviteConfig: this.data.inviteConfig,
                    isCaptain,
                    captainId
                  },
                }]
                this.setData({
                  myTeamData: this.data.myTeamData.concat(join)
                })
              }
              wx.hideLoading()
            })
          })
          .catch(error => {
            wx.hideLoading()
            wx.showToast({
              title: error,
              icon: 'none'
            })
            console.log('eventConfiguration/listManageOrganize 获取当前队伍错误!', error)
          })
      })
  },
  addPlayer () {
    wx.navigateTo({
      url: '/pages/eventConfiguration/pages/searchIt/index'
    })
  },
  /**
   * @see 跳转到信息采集页面
   */
  exchangeMask ({ id }) {
    wx.redirectTo({
      url: `/pages/eventConfiguration/pages/formCollection/index?currentUserId=${id}`
    })
  },
  /**
   * @see 点击按钮跳转到xxx页面
   */
  nextStep (e) {
    //       是否完成     是否兑换 用户id
    const { isComplete, status, id } = e.detail.teamCard
    if (status !== 2) {
      wx.navigateTo({
        url: `/pages/eventConfiguration/pages/prizeCollection/index?id=${id}`
      })
      // console.log('状态为已提交地址,触发事件为: 跳转奖品领取页面')
    } else if (isComplete) {
      this.exchangeMask({ id })
      // console.log('任务已完成,触发事件为兑换口罩 用户id为: ', id)
    } else {
      wx.navigateTo({
        url: `/pages/eventConfiguration/pages/inviteFriends/inviteFriends?btnStatus=0&currentTeam=${JSON.stringify(e.detail)}`
      })
      // console.log('任务未完成,当前已有队伍,无法创建')
    }
    this.setData({
      currentUserId: id
    })
  },
  /**
   * @see 点击查看详情
   */
  capsuleClick (e) {
    let query = {
      memberData: e.detail.memberData,
      teamCard: e.detail.teamCard,
    }
    for (const key in query) {
      if (!query[key]) {
        delete query[key]
      }
    }
    let arr = []
    for (arr in query);
    if (!arr.length) {
      query = e.currentTarget.dataset.item
    }
    query.teamCard.timeArr = []
    wx.redirectTo({
      url: `/pages/eventConfiguration/pages/inviteFriends/inviteFriends?currentTeam=${JSON.stringify(query)}`
    })
  },
  /**
   * @see 加载失败点击重试
   */
  clickMsgButton () {
    this.setData({
      appMsg: { type: 'err', show: false }
    })
    this.getCurrentTeamInfo()
  },
})